package com.sq.goodline.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sq.goodline.config.UdpConfig;
import com.sq.goodline.controller.dto.AudioDetailPushDto;
import com.sq.goodline.controller.dto.CallDetailPushDto;
import com.sq.goodline.controller.dto.CallDetailPushResultDto;
import com.sq.goodline.dao.AudioDetailDao;
import com.sq.goodline.dao.CallDetailDao;
import com.sq.goodline.dao.po.AudioDetail;
import com.sq.goodline.dao.po.CallDetail;
import com.sq.goodline.util.http.HttpClientUtil;
import com.sq.goodline.util.http.HttpResult;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class PushToPartnerService {

	@Resource
	private UdpConfig udpconfig;
	@Autowired
	HttpClientUtil httpClientUtil;
	@Autowired
	AudioDetailDao audioDetailDao;
	@Autowired
	CallDetailDao callDetailDao;
	
	/**
	 * 推送话单数据给合作方
	 * @param callDetail
	 */
	public void pushCallDetail() throws Exception {
		QueryWrapper<CallDetail> qw = new QueryWrapper<>();
		qw.in("push_result", 0,2);//0待推送，2推送失败
		qw.orderByAsc("create_time");//升序排列
		qw.last("LIMIT 50");//最多查50笔
		List<CallDetail> callDetailList = callDetailDao.selectList(qw);
		if(callDetailList==null||callDetailList.size()==0) {
			log.debug("无待推送话单");
			return;
		}
		
		List<CallDetailPushDto> cicPushList = new ArrayList<>();
		for(CallDetail callDetail:callDetailList) {
			if(callDetail.getCallergatewayid().contains("cic")) {//中华
				CallDetailPushDto dto = new CallDetailPushDto();
				dto.setFlowno(callDetail.getFlowno());
				dto.setCallere(callDetail.getCalleraccesse164());//原始主叫
				dto.setCalleee(callDetail.getCalleee164());//真实被叫
				dto.setEnddirection(callDetail.getEnddirection());
				dto.setFee(callDetail.getFee());
				dto.setFeetime(callDetail.getFeetime());
				dto.setHoldtime(callDetail.getHoldtime());
				dto.setStarttime(callDetail.getStarttime());
				dto.setStoptime(callDetail.getStoptime());
//				dto.setRecordFileUrl(null); //url待与本地rec文件关联再推送
				dto.setCid(callDetail.getCid());
				cicPushList.add(dto);
			}
		}
		if(cicPushList.size()>0) {
			pushCallDetailToCic(cicPushList);
		}
	}
	
	/**
	 * 话单数据推送给中华
	 */
	public void pushCallDetailToCic(List<CallDetailPushDto> list ) throws Exception {
		String cicUrl = udpconfig.getCallDetailPushMap().get("cic");
		String jsonStr = JSON.toJSONString(list);
		log.info("话单数据推送地址：{}",cicUrl);
		log.info("话单数据推送报文：{}",jsonStr);
		if(StringUtils.isBlank(cicUrl)) {
			return;
		}
		
		HttpResult httpResult = httpClientUtil.doPostJson(cicUrl, jsonStr);
		if(200!=httpResult.getStatusCode()){
			log.error("推送失败，状态码：{}",httpResult.getStatusCode());
		}else {
			String responseJson = httpResult.getContent();
			log.info("推送完成,响应报文：{}",responseJson);
			List<CallDetailPushResultDto> resultList = JSON.parseArray(responseJson, CallDetailPushResultDto.class);
			if(resultList!=null) {
				for(CallDetailPushResultDto resultDto:resultList) {
					if(resultDto.getResult()!=1) {
						log.info("话单推送失败，flowno:{},状态：{}",resultDto.getFlowno(),resultDto.getResult());
						resultDto.setResult(2);//推送失败统一状态为2
					}
					int i = callDetailDao.updateResultById(resultDto);
					log.info("更新推送状态完成：flowno:{},{}",resultDto.getFlowno(),i);
				}
			}
		}
	}
	
	/**
	 * 录音URL推送中华wav格式
	 * URL增加：&format=wav
	 * @throws Exception 
	 */
	public void pushAudioDetail() throws Exception {
		QueryWrapper<AudioDetail> qw = new QueryWrapper<>();
		qw.in("push_result", 0,2);//数据推送结果：-1 初始数据,0待推送、1成功，2失败
		qw.orderByAsc("create_time");//升序排列
		qw.last("LIMIT 50");//最多查50笔
		List<AudioDetail> audioDetailList = audioDetailDao.selectList(qw);
		if(audioDetailList==null||audioDetailList.size()==0) {
			log.debug("无待推送录音");
			return;
		}
		
		List<AudioDetailPushDto> cicPushlist= new ArrayList<>();
		for(AudioDetail detail:audioDetailList) {
			if(detail.getCallergatewayid().contains("cic")) {//中华
				AudioDetailPushDto pushDto = new AudioDetailPushDto();
				pushDto.setFlowno(detail.getFlowno());
				pushDto.setCid(detail.getCid());
				//中华URL需要下载wav格式
				pushDto.setRecordFileUrl(udpconfig.getDownUrlPre()+detail.getRecordFileUrl()+"&format=wav");
				cicPushlist.add(pushDto);
			}
		}
		if(cicPushlist.size()>0) {
			pushAudioToCic(cicPushlist);
		}
	}
	
	/**
	 * 录音URL推送给中华
	 * @param pushlist
	 * @throws Exception
	 */
	private void pushAudioToCic(List<AudioDetailPushDto> pushlist) throws Exception {
		String cicUrl = udpconfig.getAudioDetailPushMap().get("cic");
		String jsonStr = JSON.toJSONString(pushlist);
		log.info("录音URL推送地址：{}",cicUrl);
		log.info("录音URL推送报文：{}",jsonStr);
		
		HttpResult httpResult = httpClientUtil.doPostJson(cicUrl, jsonStr);
		if(200!=httpResult.getStatusCode()){
			log.error("推送失败，状态码：{}",httpResult.getStatusCode());
		}else {
			String responseJson = httpResult.getContent();
			log.info("推送完成,响应报文：{}",responseJson);
			List<CallDetailPushResultDto> resultList = JSON.parseArray(responseJson, CallDetailPushResultDto.class);
			if(resultList!=null) {
				for(CallDetailPushResultDto resultDto:resultList) {
					if(resultDto.getResult()!=1) {
						log.info("录音推送失败，flowno:{},状态：{}",resultDto.getFlowno(),resultDto.getResult());
						resultDto.setResult(2);//推送失败统一状态为2
					}
					int i = audioDetailDao.updateResultById(resultDto);
					log.info("更新录音推送状态完成：flowno:{},{}",resultDto.getFlowno(),i);
				}
			}
		}
	}
}
